package com.glory.brepda.activity.mfg;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.activity.check.CheckDescActivity;
import com.glory.brepda.activity.technicalservice.QCConfirmActivity;
import com.glory.brepda.adapter.GroupEqpListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.EquCallOutStateEntity;
import com.glory.brepda.entity.EquThirdStateEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.entity.stateChangeEntity;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import android.content.Intent;
public class eqpStateCompleteActivity extends BaseActivity {
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.flParentStateList)
    FrameLayout flParentStateList;
    @BindView(R.id.ivParentStateArrow)
    ImageView ivParentStateArrow;
    @BindView(R.id.tvParentState)
    TextView tvParentState;

    @BindView(R.id.remark)
    FreeUI_ClearEditText remark;


    private FreeUI_GeneralPop parentStatePop;

    private Set<String> parentStateSet = new HashSet<>();

    private GroupEqpListAdapter myAdapter;

    private Map<String, EquThirdStateEntity.EquSubStateEntity> stateMap = new HashMap<>();

    private boolean isEmpty = false;

    private Activity activity;

    @Override
    protected int getLayoutResId() {
        return R.layout.create_equipment_state_dialog;
    }

    LinearLayout equStateLine;
    Bundle bundle;

    @Override
    protected void initView() {
        equStateLine = findViewById(R.id.euqStateLine);
        bundle = getIntent().getExtras();
        setMainLayout(llMain);
        activity = this;
        myAdapter = new GroupEqpListAdapter(null,false);
        myAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        myAdapter.isFirstOnly(true);
        tvParentState.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        });

    }

    @Override
    protected void initData() {
        getEqpStatus();

    }

    private void getEqpStatus() {
        FreeUI_EntityCallBack<BaseResponseBean<EquThirdStateEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<EquThirdStateEntity>>
                (new TypeToken<BaseResponseBean<EquThirdStateEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EquThirdStateEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    List<EquThirdStateEntity.EquSubStateEntity> tempStateList = response.body().getResponse().getBody().getSTATESHEETLTEMLINELIST();
                    if(tempStateList.isEmpty()){
                        isEmpty = true;
                        equStateLine.setVisibility(View.GONE);
                    }else{
                        equStateLine.setVisibility(View.VISIBLE);
                        for (EquThirdStateEntity.EquSubStateEntity state : tempStateList) {
                            parentStateSet.add(state.getEqu_name());
                            stateMap.put(state.getEqu_name(),state);
                        }
                    }


                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EquThirdStateEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "getEqpStatus");
            }
        };
         //查询设备叫修子状态
        parentStateSet.clear();
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","QUERYSTUBSTATE");
        map.addProperty("RAS_EQP_STATE_OBJECT_RRN",bundle.getLong("RAS_EQP_STATE_OBJECT_RRN"));
        NetUtils.requestPostNet("IF.BREEQUCALLOUTMAINTAIN","Common", eqpStateCompleteActivity.this,map,callBack);
    }

    @OnClick({R.id.flParentStateList,R.id.submitButton})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.flParentStateList) {

            parentStatePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flParentStateList.getWidth(), new ArrayList<>(parentStateSet), ivParentStateArrow, (codeS, i) -> {
                tvParentState.setText(codeS);
            });
            FreeApi_PopUtils.setArrowShow(ivParentStateArrow);
            parentStatePop.showAsDropDown(flParentStateList, 0, 0);
        }else if (view.getId() == R.id.submitButton){
            if(!isEmpty){
                if(tvParentState.getText()==null||"".equals(tvParentState.getText().toString())){
                    showToast("设备状态不能为空", false);
                    return;
                }
            }
            if(remark.getText()!=null){
                if("".equals(remark.getText().toString())){
                    showToast("备注不能为空", false);
                    return;
                }
            }
            //如果设备状态子状态集合为空，提交的时候直接完工，不生成qc任务
            if(isEmpty){
                requestCompletePostNet();
            }else{
                submitChange();
            }
        }

    }

    private void submitChange() {
        FreeUI_EntityCallBack<BaseResponseBean<EquCallOutStateEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<EquCallOutStateEntity>>
                (new TypeToken<BaseResponseBean<EquCallOutStateEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EquCallOutStateEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    String resultflag = response.body().getResponse().getBody().getRESULTFLAG();
                    if("OK".equals(resultflag)){
                        requestQcCompletePostNet();
                    }else{
                        loadError(response.getException(), "eqpStateCompleteActivity");
                    }
                }


            }

            @Override
            public void onError(Response<BaseResponseBean<EquCallOutStateEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "UpdateEquipmentState");
            }
        };

        List<String > equipment = new ArrayList<>();
        equipment.add(bundle.getString("EQUIPMENT"));
        JsonObject map = new JsonObject();
        if(tvParentState.getText()!=null){
            map.addProperty("SUBCODE",stateMap.get(tvParentState.getText().toString()).getEqu_state());
        }
        map.addProperty("LOT_ID",bundle.getString("LOTID"));
        map.addProperty("CALLOUT_MAINTAIN_RRN",bundle.getLong("CALLOUT_MAINTAIN_RRN"));
        map.addProperty("RAS_EQP_STATE_OBJECT_RRN",bundle.getLong("RAS_EQP_STATE_OBJECT_RRN"));
        map.addProperty("TEXT",remark.getText().toString().trim());
        map.addProperty("ROLE","tech_timing");
        map.add("EQUIPMENT", new JsonParser().parse(new Gson().toJson(equipment)).getAsJsonArray());//设备ID

        NetUtils.requestPostNet("IF.BATCHGENERATECPCQCFORM","Common", eqpStateCompleteActivity.this,map,callBack);
    }


    public void requestQcCompletePostNet() {
        FreeUI_EntityCallBack<BaseResponseBean<EquCallOutStateEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<EquCallOutStateEntity>>
                (new TypeToken<BaseResponseBean<EquCallOutStateEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EquCallOutStateEntity>> response) {
                AlertDialog.Builder builder = new AlertDialog.Builder(eqpStateCompleteActivity.this);
                builder.setTitle("提交成功");
                builder.setMessage("提交成功并生成QC任务，请前往QC校验功能完成QC校验任务");
                builder.setPositiveButton("确定", (dialog, which) -> navigateToIndex());
                builder.setCancelable(false); // 禁止通过返回键关闭对话框

                AlertDialog dialog = builder.create();
                dialog.show();
            }

            @Override
            public void onError(Response<BaseResponseBean<EquCallOutStateEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "eqpStateComplete");
            }
        };
        JsonObject map = new JsonObject();
        if(tvParentState.getText()!=null){
            map.addProperty("SUBCODE",stateMap.get(tvParentState.getText().toString()).getEqu_state());
        }
        map.addProperty("ACTIONTYPE","COMPLETION");
        map.addProperty("OBJECTRRN",bundle.getLong("CALLOUT_MAINTAIN_RRN"));
        map.addProperty("STATE","CHECK");
        map.addProperty("ROLE","tech_timing");
        map.addProperty("REMARK",remark.getText().toString().trim());
        NetUtils.requestPostNet("IF.BREEQUCALLOUTMAINTAIN","Common", eqpStateCompleteActivity.this,map,callBack);

    }

    private void navigateToIndex() {
        Intent intent = new Intent(eqpStateCompleteActivity.this, EquipmentCallOutMaintainActivity.class);
        activity.startActivityForResult(intent,1);
        finish();
    }

    public void requestCompletePostNet() {
        FreeUI_EntityCallBack<BaseResponseBean<EquCallOutStateEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<EquCallOutStateEntity>>
                (new TypeToken<BaseResponseBean<EquCallOutStateEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EquCallOutStateEntity>> response) {
                showConfirmDialog(eqpStateCompleteActivity.this, "提交成功");
                Intent intent = new Intent(eqpStateCompleteActivity.this, EquipmentCallOutMaintainActivity.class);
                activity.startActivityForResult(intent,1);
                finish();

            }

            @Override
            public void onError(Response<BaseResponseBean<EquCallOutStateEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "eqpStateComplete");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","COMPLETION");
        map.addProperty("STATE","FIN");
        map.addProperty("OBJECTRRN",bundle.getLong("CALLOUT_MAINTAIN_RRN"));
        map.addProperty("REMARK",remark.getText().toString().trim());
        NetUtils.requestPostNet("IF.BREEQUCALLOUTMAINTAIN","Common", eqpStateCompleteActivity.this,map,callBack);

    }

}
